﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    public class HttpController : Controller
    {
        // GET: Http
        public ActionResult Request()
        {
          
            return View();
        }

        public ActionResult StreamCeshi()
        {     
            var path = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
            var filename = "ceshi.txt";
            var fileWname = "cehis.txt";
            var str = "nihao,LHarrison";

            //二进制流
            using (BinaryWriter bw = new BinaryWriter(System.IO.File.Open(path + filename, FileMode.OpenOrCreate)))
            {
                   // bw.Write()
            }
            using (BinaryReader br=new BinaryReader (System.IO.File.Open(path+filename,FileMode.OpenOrCreate)))
            {
                   // br.Read
            }
            System.IO.DriveInfo[] di = System.IO.DriveInfo.GetDrives();
            foreach (var item in di)
            {
                var s = item.AvailableFreeSpace/(1024*1024*1024);
                var ss = item.DriveFormat;
                var sss = item.DriveType;
                var s4 = item.IsReady;
                var s5 = item.Name;
                var s6 = item.RootDirectory;
                var s7 = item.TotalFreeSpace / (1024 * 1024 * 1024);
                var s8 = item.TotalSize / (1024 * 1024 * 1024);
                var s9 = item.VolumeLabel;
            }

            string[] arg = Environment.GetCommandLineArgs();
            // If a directory is not specified, exit program.
            if (arg.Length != 2)
            {
               // D:\\documents\\visual studio 2015\\Projects\\网站项目接口测试\\网站项目接口测试
                // Display the proper way to call the program.
                Console.WriteLine("Usage: Watcher.exe (directory)");
                //  return;
                arg[1] = "D:\\documents\\visual studio 2015\\Projects\\网站项目接口测试\\网站项目接口测试";
            }

            using (StreamReader sr=new StreamReader (path + fileWname))
            {
                var ch = new char[sr.BaseStream.Length];
                sr.Read(ch, 0, ch.Length);
                StringBuilder builder = new StringBuilder();
                foreach (char item in ch)
                {
                    if (char.IsLetterOrDigit(item)||char.IsWhiteSpace(item))
                    {
                        builder.Append(item);
                    }
                }
            }
            // Create a new FileSystemWatcher and set its properties.
            using (FileSystemWatcher watcher = new FileSystemWatcher())
            {
                watcher.Path = arg[1];

                // Watch for changes in LastAccess and LastWrite times, and
                // the renaming of files or directories.
                watcher.NotifyFilter = NotifyFilters.LastAccess
                                     | NotifyFilters.LastWrite
                                     | NotifyFilters.FileName
                                     | NotifyFilters.DirectoryName;

                // Only watch text files.
                watcher.Filter = "*.txt";

                // Add event handlers.
                watcher.Changed += (o,s)=> {
                    // Specify what is done when a file is changed, created, or deleted.
                    Console.WriteLine($"File: {s.FullPath} {s.ChangeType}");
                };
                watcher.Created += (o, s) => {

                };
                watcher.Deleted += (o, s) => {

                };
                watcher.Renamed += (o, s) => {
                    // Specify what is done when a file is renamed.
                    Console.WriteLine($"File: {s.OldFullPath} renamed to {s.FullPath}");
                };

                // Begin watching.
                watcher.EnableRaisingEvents = true;

                // Wait for the user to quit the program.
               // Console.WriteLine("Press 'q' to quit the sample.");
                //while (Console.Read() != 'q') ;
            }
            byte[] w = System.Text.Encoding.UTF8.GetBytes(str);
            using (FileStream n = new FileStream(path + filename, FileMode.OpenOrCreate))
            {
                n.Write(w, 0, w.Length);
            }
            using (FileStream sr = new FileStream(path + filename, FileMode.OpenOrCreate))
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                char[] bt = new char[1024];
                byte[] buffer = new byte[1024];
                UTF8Encoding utf8 = new UTF8Encoding(true);
                while (sr.Read(buffer, 0, buffer.Length) > 0)
                {
                    var si = utf8.GetString(buffer);
                    sb.Append(si);
                    Array.Clear(buffer, 0, buffer.Length);
                }
            }
            using (StreamWriter sw = new StreamWriter(path + fileWname))
            {
                using (StreamReader sr = new StreamReader(path + filename))
                {
                    char[] c = new char[1024];
                    if (sr.Read(c, 0, c.Length) != -1)
                    {
                        sw.Write(c);
                    }
                }

            }
            using (MemoryStream ms = new MemoryStream())
            {
                using (System.Drawing.Bitmap bm = new System.Drawing.Bitmap(300, 300))
                {
                    using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bm))
                    {
                        System.Drawing.Pen p = new System.Drawing.Pen(System.Drawing.Color.Red, 22);
                        g.DrawLine(p, 0, 0, 200, 200);
                        g.DrawRectangle(p
                            , new System.Drawing.Rectangle(0, 0, 10, 10));

                        // bm.Save(path + "se.png");
                        bm.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                        byte[] bte = new byte[ms.Length];
                        ms.Seek(0, SeekOrigin.Begin);
                        ms.Read(bte, 0, bte.Length);
                        var base64 = Convert.ToBase64String(bte);
                        ViewBag.base64 = "data:image/png;base64," + base64;
                    }
                }

            }
            using (MemoryStream ms = new MemoryStream())
            {
                using (Bitmap bm = new Bitmap(200, 50))
                {
                    using (Graphics g = Graphics.FromImage(bm))
                    {
                        var rd = new Random();
                        var nu = rd.Next(100000, 999999).ToString();
                       // g.DrawString(nu, new Font("宋体", 40), Brushes.Blue, 0, 0);    
                        // 清除画面，填充背景
                        g.Clear(Color.White);
                        // 画一个边框
                        //g.DrawRectangle(new Pen(Color.Gray, 0), 0, 0, map.Width-1, map.Height - 3);
                        //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;//模式
                        // 背景噪点生成                        
                        string[] BrushName = new string[] {    "OliveDrab", "ForestGreen","DarkCyan","LightSlateGray",
                                                  "RoyalBlue","SlateBlue","DarkViolet","MediumVioletRed","IndianRed",
                                                  "Firebrick","Chocolate","Peru"," enrod" };

                     
                        for (int n = 0; n < 100; n++)
                        {               
                            int x = rd.Next(bm.Width);
                            int y = rd.Next(bm.Height);
                            g.DrawRectangle(new Pen(Color.FromName(BrushName[rd.Next(12)]), 1), x, y, 1, 1);
                            //System.Threading.Thread.Sleep(10);                              
                        }
                     
                        // 验证码旋转，防止机器识别
                        // 拆散字符串成单字符数组
                        char[] chars = nu.ToCharArray();  
                        // 文字距中
                        StringFormat format = new StringFormat(StringFormatFlags.NoClip);
                        format.Alignment = StringAlignment.Center;
                        format.LineAlignment = StringAlignment.Center;
                        // 定义颜色
                        Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Brown, Color.DarkCyan, Color.Purple, Color.DarkGreen };
                        // 定义字体
                        //string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial","Lucida Sans Unicode", Rockwell, Batang ,Times New Roman,Bernard MT Condensed};
                        // 随机转动角度
                        int randAngle = 45;
                        for (int q = 0; q < chars.Length; q++)
                        {
                            int cindex = rd.Next(7);
                            int findex = rd.Next(4);

                            // 字体样式(参数2为字体大小)
                            Font f = new System.Drawing.Font("Microsoft Sans Serif", 17, System.Drawing.FontStyle.Bold);
                            Brush b = new System.Drawing.SolidBrush(c[cindex]);

                            Point dot = new Point(23, 15);
                            // 测试X坐标显示间距的
                            //graph.DrawString(dot.X.ToString(),fontstyle,new SolidBrush(Color.Black),10,150);
                            // 转动的度数
                            float angle = rd.Next(-randAngle, randAngle);

                            // 移动光标到指定位置
                            g.TranslateTransform(dot.X, dot.Y);
                            g.RotateTransform(angle);
                            g.DrawString(chars[q-0].ToString(), f, b, 1, 10, format);
                            //graph.DrawString(chars[i].ToString(),fontstyle,new SolidBrush(Color.Blue),1,1,format);
                            // 转回去
                            g.RotateTransform(-angle);
                            // 移动光标到指定位置
                            g.TranslateTransform(3, -dot.Y);
                        }
                        // 标准随机码
                        //graph.DrawString(randomcode,fontstyle,new SolidBrush(Color.Blue),2,2);
                        
                        //g.DrawRectangle(pnum, 0, 0, 200, 100);
                        bm.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                        byte[] bt = new byte[ms.Length];
                        ms.Seek(0, SeekOrigin.Begin);
                        ms.Read(bt, 0, bt.Length);
                        var base64 = Convert.ToBase64String(bt);
                        ViewBag.code = "data:image/png;base64," + base64;
                    }
                }

            }
            return View();
        }


    }
}